package com.example.myapplication

import android.app.ActivityManager
import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.util.Log
import java.util.*
/**
 * App生命周期的服务检测
 */
class AppLifeService : Service() {
    private var isAppStart = false // 判断软件是否打开，过滤重复执行
    private var packageName_now = "com.example.myapplication" //记录当前所在应用的包名
    private var timer: Timer = Timer()
    private val task = object : TimerTask() {
        override fun run() {
            val message = Message.obtain()
            message.what = 1
            handler.sendMessage(message)
        }
    }
    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            if (msg.what == 1) {
                val runningProcess = isRunningProcess(packageName_now)
                Log.e("AppLifeService" , "runningProcess $packageName_now isRun = $runningProcess")
            }
            super.handleMessage(msg)
        }
    }

    private lateinit var activityManager: ActivityManager
    override fun onCreate() {
        activityManager = getSystemService(ACTIVITY_SERVICE) as ActivityManager
        //开始监听应用，每500毫秒查询一次
        timer.schedule(task, 0, 500);
        super.onCreate()
    }

    override fun onDestroy() {
        Log.e("AppLifeService" , "onDestroy")
        timer.cancel();//销毁服务的时候同时关闭定时器timer
        super.onDestroy()
    }

    private fun isRunningProcess(packetName: String): Boolean {
        activityManager.runningAppProcesses?.forEach {
            if (TextUtils.equals(it.processName, packetName)) {
                return true;
            }
        }
        return false;
    }

    private fun topApp(){
        val am = activityManager
        val cn = am.getRunningTasks(1).get(0).topActivity;//获取到栈顶最顶层的activity所对应的应用
        val packageName = cn?.packageName//从ComponentName对象中获取到最顶层的应用包名
        if (!packageName_now.equals(packageName)) {//如果两个包名不相同，那么代表切换了应用
            packageName_now = packageName!!//更新当前的应用包名
            isAppStart = false//将是否是监听的应用包名的状态修改为false
        }
        if (packageName.equals("com.tencent.mobileqq")) {//这里举例监听QQ
            if (!isAppStart) {
                isAppStart = true;//因为一直在循环，所以需要加个isAppStart判断防止代码重复执行

            }
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
}